import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import dayjs from 'dayjs';
import { JwtService } from '@nestjs/jwt';
import { Result } from '../../dto/result.type';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../user/models/user.entity';
import { Repository } from 'typeorm';
import { encryptPassword } from '../../util';
import { ENCRYPT_SALT } from '../../constant';
import { Student } from '../student/models/student.entity';

@Injectable()
export class LoginService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
    @InjectRepository(User)
    private UserRepository: Repository<User>,
    @InjectRepository(Student)
    private StudentRepository: Repository<Student>,
  ) {}

  async login(
    tel: string,
    code: string,
    account: string,
    password: string,
    isStudent: boolean,
  ): Promise<Result> {
    //手机号登录

    if (tel) {
      const user = await this.userService.findUserByTel(tel);
      if (user.code === code) {
        if (dayjs().diff(dayjs(user.codeCreateAt)) > 60 * 5 * 1000) {
          return {
            code: false,
            message: '验证码已经失效，请重新发送验证码',
          };
        }
        const token = this.jwtService.sign({
          id: user.id,
        });
        return {
          code: true,
          message: 'true',
          data: token,
        };
      }
      if (!user) {
        return {
          code: false,
          message: '该手机号不存在!',
          data: '',
        };
      }
      return {
        code: false,
        message: '验证码错误!',
        data: '',
      };
    }
    // 密码登录
    let user;
    if (isStudent) {
      user = await this.StudentRepository.findOne({
        where: {
          account,
        },
      });
    } else {
      user = await this.UserRepository.findOne({
        where: {
          account,
        },
      });
    }

    if (!user) {
      return {
        code: false,
        message: '该用户不存在',
        data: '',
      };
    }
    const token = this.jwtService.sign({
      id: user.id,
    });
    const hashPwd = encryptPassword(password, ENCRYPT_SALT);
    if (hashPwd !== user.password) {
      return {
        code: false,
        message: '密码错误',
        data: '',
      };
    }
    return {
      code: true,
      message: '验证通过',
      data: token,
    };
  }
}
